#include "xrequest.h"
#include <string.h>
#include <stdio.h>
#include "xheader.h"
#include "msg.h"
#include "xcontent.h"
#include "libxsip.h"

XSIPRequest::XSIPRequest()
	: XSIPMessage(XSIPMessage::REQUEST_MESSAGE)
{
	m_requests = NULL;
	m_requestCount = 0;
}

XSIPRequest::~XSIPRequest()
{
	if (m_requests)
	{
		for (int i = 0; i < m_requestCount; i ++)
		{
			m_requests[i]->setHeader(NULL);
			delete m_requests[i];
		}
		delete []m_requests;
	}
	m_requestCount = 0;
}

void* XSIPRequest::getObject(const char* name) const
{
	if (strcmp(name, "XSIPRequest") == 0)
		return const_cast<XSIPRequest*>(this);
	else
		return XSIPMessage::getObject(name);
}

void XSIPRequest::divide()
{
	XSIPContent *content = getContent();
	int headerSize = getHeader()->getHeaderSize();
	XSIPContent** contents = content->divide(XSIPEngine::getCurrentThreadEngine()->getMTU()-headerSize, &m_requestCount);
	if (m_requestCount > 1)
	{
		m_requests = new XSIPRequest*[m_requestCount];
		for (int i = 0; i < m_requestCount; i ++)
		{
			m_requests[i] = new XSIPRequest();
			m_requests[i]->setHeader(getHeader());
			m_requests[i]->setContent(contents[i]);
		}
	}
	else
		m_requestCount = 0;
}

void XSIPRequest::divide(int step)
{
	XSIPContent *content = getContent();
	XSIPContent** contents = content->divide(step, &m_requestCount);
	if (m_requestCount > 1)
	{
		m_requests = new XSIPRequest*[m_requestCount];
		for (int i = 0; i < m_requestCount; i ++)
		{
			m_requests[i] = new XSIPRequest();
			m_requests[i]->setHeader(getHeader());
			m_requests[i]->setContent(contents[i]);
		}
	}
	else
		m_requestCount = 0;
}

XSIPRequest* XSIPRequest::subRequest(int i)
{
	return m_requests[i];
}

int XSIPRequest::getRequestCount()
{
	return m_requestCount;
}